﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using TNO.Education.Helpers;

namespace TNO.Education.SearchResult
{
    public partial class SearchResultUserControl : BaseControl
    {

        #region Constant

        const string ListUrl = "{0}?i={1}&p={2}&l=1";
        const string DetailUrl = "{0}?i={1}&p={2}";
        const int PageSize = 10;

        #endregion

        #region Properties

        private SearchResult _webPart;
        public SearchResult WebPart
        {
            get
            {
                if (_webPart == null)
                    _webPart = this.Parent as SearchResult;
                return _webPart;
            }
        }

        /// <summary>
        /// List by the university
        /// </summary>
        private bool ListAll
        {
            get { return Page.Request.QueryString["l"] == "1"; }
        }

        #endregion

        #region Events
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUniversityCombo();

                // Get request query strings
                string studentNumber = Page.Request.QueryString["SBD"];
                string universNumber = Page.Request.QueryString["u"];
                bool isDetails = !string.IsNullOrEmpty(Page.Request.QueryString["i"]);

                // Show watermark string in the empty case
                this.txtName.Text = studentNumber ?? this.txtName.ToolTip;
                this.ddlUniversity.SelectedValue = universNumber;

                if (isDetails)
                {
                    int pageNumber = string.IsNullOrEmpty(Page.Request.QueryString["p"]) ? -1 : Convert.ToInt32(Page.Request.QueryString["p"]);
                    int id = Convert.ToInt32(Page.Request.QueryString["i"]);

                    LayoutDetails(id, ListAll, pageNumber);
                }
                else if (!string.IsNullOrEmpty(studentNumber) && !string.IsNullOrEmpty(universNumber))
                {
                    btnSearch_Click(btnSearch, e);
                }
                else
                {
                    LayoutNotification();
                }
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pnlResult.Controls.Clear();

            if (string.IsNullOrEmpty(ddlUniversity.SelectedValue))
            {
                using (HtmlHelper htmlHelper = new HtmlHelper())
                {
                    htmlHelper.AddClass("error-tcdt");
                    htmlHelper.WriteLine(HtmlTag.Div, "Chọn trường cần tuyển sinh.");
                    pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
                }
            }
            else if (string.IsNullOrEmpty(txtName.Text)
                || txtName.Text == txtName.ToolTip)
            {
                using (HtmlHelper htmlHelper = new HtmlHelper())
                {
                    htmlHelper.AddClass("error-tcdt");
                    htmlHelper.WriteLine(HtmlTag.Div, "Số báo danh không được bỏ trống.");
                    pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
                }
            }
            else if (txtName.Text.Trim().Length == 0)
            {
                using (HtmlHelper htmlHelper = new HtmlHelper())
                {
                    htmlHelper.AddClass("error-tcdt");
                    htmlHelper.WriteLine(HtmlTag.Div, "Số báo danh nhập không hợp lệ.");
                    pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
                }
            }
            else
            {
                string key = this.BaseUrl + '_' + ddlUniversity.SelectedValue + '_' + txtName.Text;
                object obj = HttpContext.Current.Cache[key];
                lock (this)
                {
                    if (obj == null)
                    {
                        obj = DataHelper.GetResults(txtName.Text, ddlUniversity.SelectedValue, WebPart.SearchEndWith);
                        HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(CacheMinutes), TimeSpan.Zero, CacheItemPriority.Default, null);
                    }
                }

                LayoutSearchResult(obj as DataTable, -1);
            }
        }

        #endregion

        #region Methods

        private void LoadUniversityCombo()
        {
            string key = this.BaseUrl + '_' + Fields.University.TableName;
            object obj = HttpContext.Current.Cache[key];
            lock (this)
            {
                if (obj == null)
                {
                    obj = DataHelper.GetAllUniversity();
                    HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero, CacheItemPriority.Default, null);
                }
            }

            ddlUniversity.DataSource = obj as DataTable;
            ddlUniversity.DataTextField = Fields.University.Title;
            ddlUniversity.DataValueField = Fields.University.Id;
            ddlUniversity.DataBind();
        }

        /// <summary>
        /// Have number new universities.
        /// </summary>
        private void LayoutNotification()
        {
            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                //DataRow[] rows = GetNewUniversity(tableCategory);

                //if (rows.Length > 0)
                //{
                //    using (htmlHelper.RenderTag(HtmlTag.P))
                //    {
                //        htmlHelper.AddClass("left");
                //        using (htmlHelper.RenderTag(HtmlTag.Div))
                //        {
                //            htmlHelper.AddAttribute("alt", "diem thi moi");
                //            htmlHelper.AddAttribute("src", "/_layouts/images/TNO.Education/New.gif");
                //            htmlHelper.WriteLine(HtmlTag.Img);
                //        }
                //        htmlHelper.AddClass("left");
                //        using (htmlHelper.RenderTag(HtmlTag.Div))
                //        {
                //            htmlHelper.AddStyle("font-weight: bolder");
                //            htmlHelper.WriteLine(HtmlTag.Div, "Các trường mới có điểm:");
                //            using (htmlHelper.RenderTag(HtmlTag.Div))
                //            {
                //                htmlHelper.AddStyle("display: inline");
                //                using (htmlHelper.RenderTag(HtmlTag.Ul))
                //                {
                //                    for (int i = 0; i < rows.Length; i++)
                //                    {
                //                        htmlHelper.WriteLine(HtmlTag.Li, rows[i][Fields.University.Title].ToString());
                //                    }
                //                }
                //            }
                //        }
                //    }
                //    htmlHelper.AddClass("clear");
                //    htmlHelper.WriteLine(HtmlTag.P);
                //}

                htmlHelper.AddClass("error-details");
                using (htmlHelper.RenderTag(HtmlTag.Div))
                {
                    // Number of universities - 1 (Select a university)
                    htmlHelper.WriteLine(string.Format(@"Đã có <span class='r'>{0}</span> trường công bố điểm thi Đại học - Cao đẳng {1}.",
                        ddlUniversity.Items.Count - 1, WebPart.Year));
                    using (htmlHelper.RenderTag(HtmlTag.Span))
                    {
                        htmlHelper.AddAttribute("alt", "diem thi moi");
                        htmlHelper.AddAttribute("src", "/_layouts/images/TNO.Education/New.gif");
                        htmlHelper.WriteLine(HtmlTag.Img);
                    }
                }

                this.pnlResult.Controls.Clear();
                this.pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
            }
        }

        private void LayoutDetails(int id, bool listAll, int currentPage)
        {
            pnlResult.Controls.Clear();

            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                // Details
                int totalPages = 0;

                StudentInfo student;
                string key = this.BaseUrl + '_' + id;
                object obj = HttpContext.Current.Cache[key];
                lock (this)
                {
                    if (obj == null)
                    {
                        student = DataHelper.GetStudentInfo(id, PageSize, out currentPage, out totalPages);
                        if (currentPage > -1)
                        {
                            student.RangeTable = DataHelper.GetStudentDetails(student, listAll, PageSize, ref currentPage, ref totalPages);
                        }
                        HttpContext.Current.Cache.Add(key, student, null, DateTime.Now.AddMinutes(CacheMinutes), TimeSpan.Zero, CacheItemPriority.Default, null);
                    }
                    else
                    {
                        student = (StudentInfo)obj;
                        student.RangeTable = DataHelper.GetStudentDetails(student, listAll, PageSize, ref currentPage, ref totalPages);
                    }
                }

                htmlHelper.AddClass("ten-ts");
                htmlHelper.WriteLine(HtmlTag.Div, string.Format("Thông tin cần biết của thí sinh: <b class='r'>{0}</b>", student.Name.ToUpper()));
                htmlHelper.AddClass("info-details");
                using (htmlHelper.WriteTag(HtmlTag.Div))
                {
                    htmlHelper.AddClass("inside-details");
                    using (htmlHelper.WriteTag(HtmlTag.Div))
                    {
                        using (htmlHelper.RenderTag(HtmlTag.Div))
                        {
                            htmlHelper.AddClass("ten-ts");
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("SBD: <b>{0}</b> - <b>{1}</b>", student.Code, student.Name.ToUpper()));
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Môn 1: <b>{0}</b>, Môn 2: <b>{1}</b>, Môn 3: <b>{2}</b>{3}{4}{5} - Tổng điểm: <b class='r'>{6}</b>", // - Điểm cộng: {7} - Tổng cộng: {8}",
                                student.Subject1, student.Subject2, student.Subject3, GetDisplayMark(student.Subject4, 4), GetDisplayMark(student.Subject5, 5), GetDisplayMark(student.Subject6, 6), student.Total)); //, student.AddMark, student.Total + student.AddMark));
                        }
                        using (htmlHelper.RenderTag(HtmlTag.Div))
                        {
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Trường: {0}", student.UniversityName));
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Ngành: {0}", student.Industry));
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Khối: {0}", student.Group));
                        }
                        using (htmlHelper.RenderTag(HtmlTag.Div))
                        {
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Thông tin thí sinh theo ngành <i>{0}</i> - Khối <i>{1}</i>:",
                                student.Industry, student.Group));
                            using (htmlHelper.RenderTag(HtmlTag.Ul))
                            {
                                //htmlHelper.WriteLine(HtmlTag.Li, string.Format("<b>Điểm chuẩn</b> năm {0}: {1}",
                                //        Year, student.StdMark));
                                //htmlHelper.WriteLine(HtmlTag.Li, string.Format("<b>Chỉ tiêu ngành</b> năm {0}: {1}",
                                //        Year, student.IndPoint));
                                //htmlHelper.WriteLine(HtmlTag.Li, string.Format("Thứ tự thí sinh theo ngành: {0}/{1}",
                                //       student.IndSeq, student.IndTotalRecords));
                                htmlHelper.WriteLine(HtmlTag.Li, string.Format("Số thí sinh theo <b>ngành cùng điểm</b>: <b class='r'>{0}</b>",
                                       student.IndEqualsToMe));
                                htmlHelper.WriteLine(HtmlTag.Li, string.Format("Số thí sinh theo <b>ngành hơn điểm</b>: <b class='r'>{0}</b>",
                                       student.IndGreaterThanMe));
                            }
                        }

                        using (htmlHelper.RenderTag(HtmlTag.Div))
                        {
                            htmlHelper.WriteLine(HtmlTag.Div, string.Format("Thông tin thí sinh theo trường <i>{0}</i>:",
                                student.UniversityName));
                            using (htmlHelper.RenderTag(HtmlTag.Ul))
                            {
                                //htmlHelper.WriteLine(HtmlTag.Li, string.Format("<b>Chỉ tiêu trường</b> năm {0}: {1}",
                                //       Year, student.UniPoint));
                                //htmlHelper.WriteLine(HtmlTag.Li, string.Format("Thứ tự thí sinh theo trường: {0}/{1}",
                                //       student.UniSeq, student.UniTotalRecords));
                                htmlHelper.WriteLine(HtmlTag.Li, string.Format("Số thí sinh theo <b>trường cùng điểm</b>: <b class='r'>{0}</b>",
                                      student.UniEqualsToMe));
                                htmlHelper.WriteLine(HtmlTag.Li, string.Format("Số thí sinh theo <b>trường hơn điểm</b>: <b class='r'>{0}</b>",
                                       student.UniGreaterThanMe));
                            }
                        }
                        htmlHelper.AddClass("note");
                        htmlHelper.WriteLine(HtmlTag.Div, "<b><i>Lưu ý: Thứ tự thí sinh theo ngành, trường được thống kê trên đây chỉ mang tính chất tham khảo.</i></b>");
                    }
                }

                //htmlHelper.WriteLine(HtmlTag.Div, string.Format("Với số điểm {0} bạn có thể trúng tuyển vào các trường sau đây:", student.Total));
                //using (htmlHelper.RenderTag(HtmlTag.Ul))
                //{
                //    for (int i = 1; i < 9; i++)
                //    {
                //        using (htmlHelper.RenderTag(HtmlTag.Li))
                //        {
                //            htmlHelper.AddAttribute("href", "#");
                //            htmlHelper.WriteLine(HtmlTag.A, string.Format("Trường Đại Học {0}", i));
                //        }
                //    }
                //}

                htmlHelper.AddClass(listAll ? "search-tab" : "search-tab selectedTab");
                htmlHelper.AddStyle("float: left");
                using (htmlHelper.RenderTag(HtmlTag.Div))
                {
                    if (listAll)
                    {
                        htmlHelper.AddAttribute("href", string.Format("{0}?i={1}", this.BaseUrl, id));
                        htmlHelper.WriteLine(HtmlTag.A, "Thứ tự theo ngành");
                    }
                    else
                        htmlHelper.WriteLine("Thứ tự theo ngành");
                }

                htmlHelper.AddClass(!listAll ? "search-tab" : "search-tab selectedTab");
                htmlHelper.AddStyle("float: left", "margin-left: 5px");
                using (htmlHelper.RenderTag(HtmlTag.Div))
                {
                    if (listAll)
                        htmlHelper.WriteLine("Thứ tự theo trường");
                    else
                    {
                        htmlHelper.AddAttribute("href", string.Format("{0}?i={1}&l=1", this.BaseUrl, id));
                        htmlHelper.WriteLine(HtmlTag.A, "Thứ tự theo trường");
                    }
                }

                pnlResult.Controls.Add(new Literal { Text = htmlHelper.ToString() });

                LayoutSearchResult(student.RangeTable, student.Id);

                Paging(student, currentPage, totalPages);
            }
        }

        private void LayoutSearchResult(DataTable table, int id)
        {
            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                if (table.Rows.Count > 0)
                {
                    htmlHelper.AddAttribute("cellspacing", "1");
                    htmlHelper.AddClass("grid-table");
                    using (htmlHelper.WriteTag(HtmlTag.Table))
                    {
                        using (htmlHelper.RenderTag("thead"))
                        {
                            using (htmlHelper.RenderTag(HtmlTag.Tr))
                            {
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "STT");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "SBD");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Họ và tên");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Khối thi");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Mã ngành");
                                htmlHelper.AddAttribute("colspan", "6");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn thi");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Tổng điểm");
                                //htmlHelper.AddAttribute("rowspan", "2");
                                //htmlHelper.WriteLine(HtmlTag.Th, "Khu vực");
                                //htmlHelper.AddAttribute("rowspan", "2");
                                //htmlHelper.WriteLine(HtmlTag.Th, "+ Ưu tiên");
                                htmlHelper.AddAttribute("rowspan", "2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Thông tin cần biết");
                            }
                            using (htmlHelper.RenderTag(HtmlTag.Tr))
                            {
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 1");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 2");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 3");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 4");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 5");
                                htmlHelper.WriteLine(HtmlTag.Th, "Môn 6");
                            }
                        }
                        using (htmlHelper.RenderTag("tbody"))
                        {
                            foreach (DataRow item in table.Rows)
                            {
                                if (id.Equals(Int32.Parse(item["ID"].ToString())))
                                {
                                    htmlHelper.AddClass("tr-selected");
                                }
                                using (htmlHelper.WriteTag(HtmlTag.Tr))
                                {
                                    htmlHelper.AddClass("td-01");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.RowId].ToString());
                                    htmlHelper.AddClass("td-02");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.SBD].ToString());
                                    htmlHelper.AddClass("td-03");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.Hoten].ToString());
                                    htmlHelper.AddClass("td-04");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.KhoiThi].ToString());
                                    htmlHelper.AddClass("td-05");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.MaNganh].ToString());
                                    htmlHelper.AddClass("td-06");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM1]));
                                    htmlHelper.AddClass("td-07");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM2]));
                                    htmlHelper.AddClass("td-08");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM3]));
                                    htmlHelper.AddClass("td-09");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM4]));
                                    htmlHelper.AddClass("td-10");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM5]));
                                    htmlHelper.AddClass("td-11");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.DM6]));
                                    htmlHelper.AddClass("td-12");
                                    htmlHelper.WriteLine(HtmlTag.Td, GetDisplayMark(item[Fields.ExamResult.TongDiem]));
                                    //htmlHelper.AddClass("td-13");
                                    //htmlHelper.WriteLine(HtmlTag.Td, item[Fields.ExamResult.KhuVuc].ToString());
                                    //htmlHelper.AddClass("td-14");
                                    //htmlHelper.WriteLine(HtmlTag.Td, (Convert.ToSingle(item[Fields.ExamResult.TongDiem]) + GetAddMark(item[Fields.ExamResult.KhuVuc].ToString())).ToString());

                                    htmlHelper.AddClass("td-15");
                                    using (htmlHelper.RenderTag(HtmlTag.Td))
                                    {
                                        htmlHelper.AddAttribute("href", string.Format("{0}?i={1}", this.BaseUrl, item[Fields.ExamResult.Id]));
                                        htmlHelper.WriteLine(HtmlTag.A, "Chi tiết");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    htmlHelper.AddClass("error-tcdt");
                    htmlHelper.WriteLine(HtmlTag.Div, "Không tìm thấy kết quả.");
                }
                pnlResult.Controls.Add(new Literal { Text = htmlHelper.ToString() });
            }
        }

        private void Paging(StudentInfo student, int currentPage, int totalPages)
        {
            int startIndex, length;
            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                htmlHelper.AddClass("clear");
                htmlHelper.WriteLine(HtmlTag.Div);

                htmlHelper.AddId("grid-paging");
                using (htmlHelper.WriteTag(HtmlTag.Ul))
                {
                    if (currentPage < 4)
                    {
                        // TO DO: 1 -> Min(5, totalPages)
                        length = Math.Min(5, totalPages);
                        startIndex = 0;
                    }
                    else
                    {
                        // TO DO: < 2 3 4 -> Min(6, totalPages)
                        length = Math.Min(currentPage + 2, totalPages);
                        startIndex = length - 5;
                    }

                    string url = ListAll ? ListUrl : DetailUrl;

                    if (startIndex > 0)
                    {
                        // TO DO: |<
                        htmlHelper.AddClass("btn");
                        using (htmlHelper.RenderTag(HtmlTag.Li))
                        {
                            htmlHelper.AddAttribute("href", string.Format(url, this.BaseUrl, student.Id, 0));
                            htmlHelper.WriteLine(HtmlTag.A, "|<");
                        }
                        // TO DO: <
                        htmlHelper.AddClass("btn");
                        using (htmlHelper.RenderTag(HtmlTag.Li))
                        {
                            htmlHelper.AddAttribute("href", string.Format(url, this.BaseUrl, student.Id, startIndex - 1));
                            htmlHelper.WriteLine(HtmlTag.A, "<");
                        }
                    }

                    for (int i = startIndex; i < length; i++)
                    {
                        if (i == currentPage) htmlHelper.AddClass("page-item-selected");
                        using (htmlHelper.RenderTag(HtmlTag.Li))
                        {
                            htmlHelper.AddAttribute("href", string.Format(url, this.BaseUrl, student.Id, i));
                            htmlHelper.WriteLine(HtmlTag.A, string.Format("{0}", i + 1));
                        }
                    }

                    if (totalPages > length)
                    {
                        // TO DO: >
                        htmlHelper.AddClass("btn");
                        using (htmlHelper.RenderTag(HtmlTag.Li))
                        {
                            htmlHelper.AddAttribute("href", string.Format(url, this.BaseUrl, student.Id, length));
                            htmlHelper.WriteLine(HtmlTag.A, ">");
                        }
                        // TO DO: >|
                        htmlHelper.AddClass("btn");
                        using (htmlHelper.RenderTag(HtmlTag.Li))
                        {
                            htmlHelper.AddAttribute("href", string.Format(url, this.BaseUrl, student.Id, totalPages - 1));
                            htmlHelper.WriteLine(HtmlTag.A, ">|");
                        }
                    }
                }

                pnlResult.Controls.Add(new Literal { Text = htmlHelper.ToString() });
            }
        }

        private float GetAddMark(string location)
        {
            switch (location)
            {
                case "1":
                    return 1.5f;
                case "2":
                    return .5f;
                case "2NT":
                    return 1f;
                default: // NULL and 3
                    return 0;
            }
        }

        private string GetDisplayMark(float? obj, int i)
        {
            return obj == null ? string.Empty : string.Format(", Môn {0}: <b>{1}</b>", i, obj.ToString());
        }

        private string GetDisplayMark(object obj)
        {
            return obj == DBNull.Value ? string.Empty : obj.ToString();
        }

        #endregion

    }
}
